<template>
  <div>
    <div class="box-shadow pad10 mgb10">
      <el-form :model="queryParams" ref="queryRef" :inline="true" class="fnmb">
        <div class="flex jbetween">
          <div>
            <el-form-item label="编号">
              <el-input
                v-model="queryParams.Code"
                placeholder="请输入"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="名称">
              <el-input
                v-model="queryParams.Name"
                placeholder="请输入"
                clearable
                style="width: 200px"
                @keyup.enter="handleQuery"
              />
            </el-form-item>
            <el-form-item label="类型">
              <el-select
                v-model="queryParams.Type"
                clearable
                placeholder="请选择"
              >
                <el-option label="学年" :value="1" />
                <el-option label="院系" :value="2" />
                <el-option label="专业" :value="3" />
                <el-option label="班级" :value="4" />
              </el-select>
            </el-form-item>
          </div>
          <div class="flex acenter fnw jend">
            <el-button type="primary" icon="Search" @click="handleQuery"
              >搜索</el-button
            >
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </div>
        </div>
      </el-form>
    </div>
    <el-row :gutter="10">
      <el-col :span="14">
        <div class="box-shadow pad10">
          <div class="head-container" style="display: flex">
            <el-button
              type="primary"
              v-hasPermi="['Class:add']"
              @click="handleAdd()"
              >添加根级</el-button
            >
          </div>
          <div class="head-container">
            <el-tree
              :data="classOptions"
              :props="{ label: 'Name', children: 'children', isLeaf: 'isLeaf' }"
              :expand-on-click-node="false"
              ref="treeRef"
              node-key="ID"
              highlight-current
              :load="loadNode"
              lazy
              @node-click="handleNodeClick"
              @node-drop="handleDrop"
            >
              <template #default="{ node, data }">
                <span class="custom-tree-node">
                  <span>{{ node.label }}</span>
                  <span>
                    <a
                      @click.stop="handleAdd(data)"
                      v-hasPermi="['Class:add']"
                      style="color: #409eff"
                      v-if="data.Type != 4"
                    >
                      添加子集
                    </a>
                    <el-popconfirm
                      title="确定删除吗？"
                      @confirm="handleDelete(node, data)"
                    >
                      <template #reference>
                        <a
                          style="margin-left: 8px; color: red"
                          v-hasPermi="['Class:delete']"
                        >
                          删除
                        </a>
                      </template>
                    </el-popconfirm>
                  </span>
                </span>
              </template>
            </el-tree>
          </div>
        </div>
      </el-col>
      <el-col :span="10">
        <div class="box-shadow pad10" v-show="editInfo.ID">
          <el-form
            :model="editInfo"
            :rules="rules"
            inline
            :label-width="80"
            ref="editFormRef"
            class="wid100"
          >
            <el-form-item label="编号" prop="Code">
              <el-input
                v-model="editInfo.Code"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
            <el-form-item label="名称" prop="Name">
              <el-input
                v-model="editInfo.Name"
                placeholder="请输入"
                clearable
              />
            </el-form-item>
            <el-form-item label="类型" prop="Type">
              <Selector
                v-model="editInfo.Type"
                :query="{
                  Type: ClassType
                }"
                category="班级类型"
              ></Selector>
            </el-form-item>
            <el-form-item
              label="负责人"
              v-if="editInfo.Type != 4"
              prop="Principal"
            >
              <Selector
                category="用户列表"
                :query="{
                  Type: 2
                }"
                v-model="editInfo.Principal"
              ></Selector>
            </el-form-item>
            <el-form-item
              label="班主任"
              v-if="editInfo.Type == 4"
              prop="Principal"
            >
              <Selector
                category="用户列表"
                :query="{
                  Type: 2
                }"
                v-model="editInfo.Principal"
              ></Selector>
            </el-form-item>
            <el-form-item label="排序" prop="Sort">
              <el-input-number
                v-model="editInfo.Sort"
                style="width: 212px"
                controls-position="right"
                :min="0"
              />
            </el-form-item>
            <el-form-item label="备注" prop="Remark">
              <el-input
                v-model="editInfo.Remark"
                type="textarea"
                style="width: 212px"
                placeholder="请输入"
                clearable
              />
            </el-form-item>

            <div>
              <el-button
                type="primary"
                size="large"
                v-hasPermi="['Class:edit']"
                style="width: 100%; border-radius: 6px; margin-bottom: 20px"
                @click="handleEdit"
                >提交修改</el-button
              >
            </div>
            <div class="subTitle">关联绑定</div>
            <div class="flex jaround acenter">
              <el-button
                type=""
                plain
                size="large"
                style="width: 40%; border-radius: 6px"
                v-if="ClassType == 3"
                @click="handleBindUser"
                >绑定用户</el-button
              >
              <el-button
                v-if="ClassType == 3"
                type=""
                plain
                size="large"
                style="width: 40%; border-radius: 6px"
                @click="handleBindCourse"
                >绑定课程</el-button
              >
            </div>
          </el-form>
        </div>
        <div v-show="!editInfo.ID" class="flex acenter" style="height: 100%">
          <div>请在左侧选择班级</div>
        </div>
      </el-col>
    </el-row>
    <MyDialog
      v-model:show="show"
      :title="title"
      :width="450"
      :formRef="formRef"
      @confirm="confirm"
    >
      <el-form
        :model="formData"
        :rules="rules"
        inline
        :label-width="80"
        ref="formRef"
        class="wid100"
      >
        <el-form-item label="上级层级">
          {{ currentName }}
        </el-form-item>
        <el-form-item label="编号" prop="Code">
          <el-input v-model="formData.Code" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="名称" prop="Name">
          <el-input v-model="formData.Name" placeholder="请输入" clearable />
        </el-form-item>
        <el-form-item label="类型" prop="Type">
          <Selector
            v-model="formData.Type"
            category="班级类型"
            :query="{
              Type: ClassType
            }"
          ></Selector>
        </el-form-item>
        <el-form-item label="负责人" v-if="formData.Type != 4" prop="Principal">
          <Selector category="全部用户" v-model="formData.Principal"></Selector>
        </el-form-item>
        <el-form-item label="班主任" v-if="formData.Type == 4" prop="Principal">
          <Selector category="全部用户" v-model="formData.Principal"></Selector>
        </el-form-item>
        <el-form-item label="排序" prop="Sort">
          <el-input-number
            v-model="formData.Sort"
            controls-position="right"
            :min="0"
          />
        </el-form-item>
        <el-form-item label="备注" prop="Remark">
          <el-input
            v-model="formData.Remark"
            type="textarea"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
      </el-form>
    </MyDialog>
    <!-- 绑定课程 -->
    <MyDialog
      v-model:show="showBindCourse"
      :title="title"
      @confirm="submitBindUser"
      :destroy="true"
    >
      <CourseBindList
        :showAdd="false"
        :classID="editInfo.ID"
        v-model:checkList="bindData"
      ></CourseBindList>
    </MyDialog>
    <!-- 绑定用户 -->
    <MyDialog
      v-model:show="showBindUser"
      :title="title"
      @confirm="submitBindUser"
      :destroy="true"
      :showAdd="false"
    >
      <UserTable
        :userColumns="userColumns"
        v-model:checkList="bindData"
        :query="{ Type: 1 }"
        :Type="true"
        :showAdd="false"
      ></UserTable>
    </MyDialog>
  </div>
</template>

<script setup name="Class">
import UserTable from '@/views/system/User/index';
import CourseBindList from '@/views/school/Class/CourseBindList';
import { getCurrentInstance, onMounted, ref, watch } from 'vue';
import {
  GetClassList,
  GetClassList_PID,
  AddClass,
  EditClass,
  DelClass,
  ClassBindUser,
  GetClassBindUserList
} from '@/api/school/class.js';
const className = ref('');
const userColumns = ref([
  { label: '多选框' },
  { label: '序号' },
  { label: '用户名称', prop: 'Name' },
  { label: '状态', tag: true, prop: 'tags' },
  { label: '电话号码', prop: 'Phone' }
  // { label: "备注", prop: "Remark", width: 300, input: true },
]);

const classOptions = ref([]);
const editInfo = ref({});
const show = ref(false);
const title = ref('');
const rules = ref({
  Code: [{ required: true, message: '请输入', trigger: 'blur' }],
  Name: [{ required: true, message: '请输入', trigger: 'blur' }],
  Principal: [{ required: true, message: '请选择', trigger: 'blur' }],
  Type: [{ required: true, message: '请选择', trigger: 'blur' }]
});
const formData = ref({});
const formRef = ref();
const { proxy } = getCurrentInstance();
const treeRef = ref();
const currentName = ref();
const subID = ref();
const editFormRef = ref();
const showBindCourse = ref(false);
const queryParams = ref({
  Code: '',
  Name: '',
  Type: '' //类型 1:学年 2:院系 3:专业 4:班级
});
const showBindUser = ref(false);
const ClassType = ref('0');
const bindData = ref([]);

watch(className, val => {
  treeRef.value?.filter(val);
});

onMounted(() => {
  // getList();
});
async function getList() {
  show.value = false;
  try {
    let res = await GetClassList_PID({ ID: 0 });
    let list = res.data?.map(item => {
      return {
        ...item.Info,
        isLeaf: !item.IsHasChild
      };
    });
    classOptions.value = list;
  } catch (error) {
    console.log(error);
  }
}

async function handleQuery() {
  try {
    let res = await GetClassList(queryParams.value);
    classOptions.value = res.data;
  } catch (error) {
    console.log(error);
  }
  // getList();
}

function resetQuery() {
  queryParams.value = {
    Code: '',
    Name: '',
    Type: '' //类型 1:学年 2:院系 3:专业 4:班级
  };
  getList();
}

async function handleBindCourse() {
  try {
    // let res = await GetClassBindCourseList({ ID: editInfo.value.ID });
    console.log(editInfo.value.ID);
    // bindData.value = res.data;
    title.value = '绑定课程';
    showBindCourse.value = true;
  } catch (error) {
    console.log(error);
  }
}

async function handleBindUser() {
  try {
    let res = await GetClassBindUserList({ ID: editInfo.value.ID });
    bindData.value = res.data;
    title.value = '绑定用户';
    showBindUser.value = true;
  } catch (error) {
    console.log(error);
  }
}

async function submitBindUser() {
  try {
    let query = {
      ID: editInfo.value.ID,
      UserIDs: bindData.value?.map(item => item.ID)
    };
    if (title.value == '绑定课程') {
      await ClassBindUser(query);
      proxy.$modal.msgSuccess('绑定成功');
      showBindUser.value = false;
    } else {
      await ClassBindUser(query);
      proxy.$modal.msgSuccess('绑定成功');
      showBindUser.value = false;
    }
  } catch (error) {
    console.log(error);
  }
}

async function confirm() {
  try {
    formRef.value.validate(async valid => {
      if (valid) {
        let query = {
          ...formData.value,
          Pid: subID.value
        };

        let res = await AddClass(query);
        proxy.$modal.msgSuccess('添加成功');
        if (subID.value != 0) {
          let node = treeRef.value.getNode(subID.value);
          node.loaded = false;
          node.loadData();
          node.loaded = true;
        } else {
          treeRef.value.append({ ...query, ID: res.data, isLeaf: true });
        }
        show.value = false;
        // getList();
      }
    });
  } catch (error) {
    console.log(error);
  }
}

async function handleDelete(node, data) {
  try {
    await DelClass({ ID: data.ID });
    proxy.$modal.msgSuccess('删除成功');
    treeRef.value.remove(node);
    if (data.ID == editInfo.value.ID) {
      editInfo.value = {};
    }
    show.value = false;
    // getList();
  } catch (error) {
    console.log(error);
  }
}

function allowDrop(draggingNode, dropNode, DropType) {
  return DropType == 'inner';
}

async function handleDrop(draggingNode, dropNode, dropType) {
  formData.value = proxy.$deepClone(draggingNode.data);
  formData.value.Pid = dropNode.data.ID;
  try {
    let query = {
      ...formData.value
    };
    await EditClass(query);
    console.log(dropNode);
    proxy.$modal.msgSuccess('修改成功');
    // treeRef.value.append(draggingNode, dropNode.data.ID);
    // getList();
  } catch (error) {
    getList();
    console.log(error);
  }
}

async function loadNode(node, resolve) {
  try {
    let res;
    if (node.level == 0) {
      res = await GetClassList_PID({ ID: 0 });
    } else {
      res = await GetClassList_PID({ ID: node.data.ID });
    }
    let list = res.data?.map(item => {
      return {
        ...item.Info,
        isLeaf: !item.IsHasChild
      };
    });
    resolve(list);
  } catch (error) {
    console.log(error);
  }
}

function refresh() {
  editInfo.value = {};
  editFormRef.value.resetFields();
  getList();
}

async function handleEdit() {
  try {
    let query = {
      ...editInfo.value
    };
    await EditClass(query);
    let node = treeRef.value.getNode(query.ID);
    node.data = query;
    proxy.$modal.msgSuccess('修改成功');
  } catch (error) {
    console.log(error);
  }
}

function handleAdd(row) {
  console.log(row);
  formData.value = {};
  show.value = true;
  if (row) {
    ClassType.value = String(row.Type);
    title.value = '添加子集';
    currentName.value = row.Name;
    subID.value = row.ID;
  } else {
    ClassType.value = '0';
    subID.value = '0';
    title.value = '添加根级';
  }
}

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.Name.indexOf(value) !== -1;
};
function handleNodeClick(val) {
  // bindData.ID = val.ID

  ClassType.value = String(Number(val.Type - 1));
  editInfo.value = proxy.$deepClone(val);
}
</script>

<style lang="scss" scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}

.subTitle {
  padding: 0 0 10px 10px;
  font-weight: bold;
}
</style>
